"""
根据关键字封装类函数
"""
import time
from selenium.webdriver.support.wait import WebDriverWait

from commons.exchange import injecting_vars, global_vars
from commons import pages


class Word:
    def __init__(self, driver):
        self.driver = driver
        self.wait = WebDriverWait(driver, 10)

    def get_msg(self):
        """获取message信息并返回"""
        msg = WebDriverWait(self.driver, 10).until(
            lambda d: d.find_element("xpath", """//p[@class="prompt-msg"]""").text)
        return msg

    def close_msg(self):
        """获取系统提示，然后关闭"""
        msg = self.get_msg()
        el_close = ("xpath", '//button[@class="am-close"]')
        self.driver.find_element(*el_close).click()
        time.sleep(1)
        return msg

    def click_by_js(self, element):
        """JS强制点击"""
        self.driver.execute_script("arguments[0].click();", element)

    def frame_exit(self):
        """从iframe切回来"""
        self.driver.switch_to.frame(None)

    def refresh(self):
        """刷新页面"""
        self.driver.refresh()

    # =====================以下方法为封装用户操作=====================
    @staticmethod
    def sleep(m):
        time.sleep(float(m))

    def goto(self, url):
        """进行页面跳转"""
        self.driver.get(url)

    def click(self, xpath):
        """点击指定元素"""
        el = self.driver.find_element("xpath", xpath)
        self.click_by_js(el)

    def send_keys(self, xpath, content):
        """对指定元素进行输入"""
        el = self.driver.find_element("xpath", xpath)
        el.send_keys(content)

    def save_attr(self, xpath, attr, var_name):
        """保存指定元素属性"""
        el = self.driver.find_element("xpath", xpath)
        value = el.get_attribute(attr)
        global_vars[var_name] = value

    def save_text(self, xpath, var_name):
        el = self.driver.find_element("xpath", xpath)
        text = el.text
        global_vars[var_name] = text

    def save_msg(self, var_name):
        """保存系统提示"""
        msg = self.close_msg()
        global_vars[var_name] = msg

    @staticmethod
    def assert_equal(a, b):
        """断言 a == b"""
        a = injecting_vars(a)
        b = injecting_vars(b)
        assert a == b

    @staticmethod
    def assert_not_equal(a, b):
        """断言 a != b"""
        a = injecting_vars(a)
        b = injecting_vars(b)
        assert a != b

    def pom(self, class_name, action, *args):
        """调用指定的pom，完成自动化"""
        page_class = getattr(pages, class_name)
        page = page_class(self.driver)
        action_func = getattr(page, action)
        # 如果args有关键字参数，如xxx.input("别名", name="新name")，要做特殊处理
        args_list = [] # 位置参数
        key_args_list = {}# 关键字参数
        for i in args:
            if isinstance(i, str) and "===" in i:
                key, value = i.split("===")
                key_args_list[key] = value
            else:
                args_list.append(i)
        action_func(*args_list, **key_args_list)
